Nothing happening on submit - Flask tut

by: cdowney102@gmail.com, 7 years ago


Following along with the practical flask app tutorial. I've gone through videos 15, 16 and 17 three times each and still can't figure this out. for debugging purposes I added some print statements and found that my code never gets passed the form.validate(), so basically, after trying to sign up, the console says "inside last statement!" but never "inside first if statement!". Anyone have any input at all...?


@app.route('/register/', methods=['GET', 'POST'])  
def register_page():
    try:
        form = RegistrationForm(request.form)
    
        if request.method == "POST" and form.validate():
            print("inside first if statement!")
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))

            c, conn = connection()
          
            x = c.execute("SELECT * FROM users WHERE username == (%s)", (thwart(username)))

            if int(x) > 0:
                flash("That username is already taken.")
                return render_template('register.html', form=form)

            else:        
                c.execute("INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)", thwart(username), thwart(password), thwart(email),
                          thwart("/introduction-to-python-programing/"))
                conn.commit()

                flash("Thanks for registering")

                c.close() #close cursor
                conn.close() #close DB connection
                gc.collect() #collect garbage - clear unused cache memory

                session['logged_in'] = True
                session['username'] = username
                return redirect(url_for('dashboard'))
        print("inside last statement!")
        return render_template('register.html', form=form)

    except Exception as e:
        return (str(e))




You must be logged in to post. Please login or register an account.



Have you tested with JUST the  if method == POST? (removing the form validation). That will tell you if you are indeed at least POSTing the data. If so, then form.validate is indeed the point of failure.

What does your form class look like?

Can you show your HTML as well?

-Harrison 7 years ago

You must be logged in to post. Please login or register an account.


Yes, I've tested with just the if method==POST and it does work, so it is the form.validate that is failing. Here's my code:

Form class:

class RegistrationForm(Form):
    username = StringField('username',[validators.Length(min=4, max=20)])#can put this validation logic here
    email = StringField('Email Address',[validators.Length(min=6, max=50)])
    password = PasswordField('Password', [validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match')])
    confirm = PasswordField('Repeat Password')

    accept_tos = BooleanField('I accept the <a href="/terms/">terms of service</a> and the <a href="/privacy/">privacy notice</a>', [validators.DataRequired()])





HTML:


{% extends "header.html" %}

{% block body %}

<body>
<div class = "container">
<h4>Register</h4>
<br>
{% from "_formhelpers.html" import render_field %}
<form method=post action="/register/">
<dl>
{{render_field(form.username)}}
{{render_field(form.email)}}
{{render_field(form.password)}}
{{render_field(form.confirm)}}
{{render_field(form.accept_tos)}}
</dl>
<p><input type=submit value=Register></p>
</form>

{% if error %}
<p class="error"><strong>Error:</strong>{{error}}</p>
{% endif %}

</div>
</body>

{% endblock %}



-cdowney102@gmail.com 7 years ago

You must be logged in to post. Please login or register an account.


BTW, I'm using pyCharm and it suggested to use StringField instead of TextField for newer versions of WTF

-cdowney102@gmail.com 7 years ago

You must be logged in to post. Please login or register an account.


You could do that, but it shouldn't be the problem. Something isn't passing validation. You could just start eliminating the validations. Just removed the "validators.XXXXX" stuff one by one til it works, or try adding them in 1 by 1 til it fails. For example, do you have the check-box for accepting ToS? Maybe that's not getting triggered for some reason...etc.

-Harrison 7 years ago

You must be logged in to post. Please login or register an account.


Just add " {{ form.hidden_tag() }}  in your html file".

-myz1105 6 months ago
Last edited 6 months ago

You must be logged in to post. Please login or register an account.

UPDATE: I tried to copy/paste your source code form that video and it still doesn't work. I'm not sure what that narrows it down to...some html code somewhere is off?

-cdowney102@gmail.com 7 years ago

You must be logged in to post. Please login or register an account.


Try doing if form.validate_on_submit(): rather than the if == post and validate.

See what happens there.

-Harrison 7 years ago

You must be logged in to post. Please login or register an account.


That didn't work. It still didn't run the first print statement. There's definitely something fishy with validate.

-cdowney102@gmail.com 7 years ago

You must be logged in to post. Please login or register an account.


Check the other reply as well regarding debugging which of the validators isn't validating.

-Harrison 7 years ago

You must be logged in to post. Please login or register an account.


So I commented out all of them and went one-by-one and still got the same results. I have no idea what it could be at this point.

-cdowney102@gmail.com 7 years ago

You must be logged in to post. Please login or register an account.


Even with none of the calls to validate anything, you still couldn't pass validation? That's pretty strange.

If you cannot get it figured out, I would suggest you simply skip this for now and revisit it fresh. The validation is purely to make sure things like passwords match and fields have been populated. You *can* simply do this via Python code yourself as well (validators is just a helper function). I am sure it's something obvious we're both missing, but no sense in banging against it for forever without progressing, especially for something that isn't of the utmost importance like this.

-Harrison 7 years ago
Last edited 7 years ago

You must be logged in to post. Please login or register an account.

I know. The reason I didn't want to move forward was because I really wanted to practice after this tutorial by making a website and this is definitely a crucial part! The main point for me of taking this tut was to learn how to program with a database.

-cdowney102@gmail.com 7 years ago

You must be logged in to post. Please login or register an account.